<template>
  <div class="doctor-prescriptions">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-info">
            <h2>关联处方查看</h2>
            <div class="breadcrumb-info" v-if="queryParams.patientName">
              <span>患者：{{ queryParams.patientName }}</span>
              <span v-if="queryParams.recordDate">就诊日期：{{ formatDate(queryParams.recordDate) }}</span>
            </div>
          </div>
          <div class="header-actions">
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon> 返回
            </el-button>
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 处方列表 -->
      <div v-loading="loading">
        <div v-if="prescriptionsList.length === 0" class="empty-state">
          <el-empty description="暂无关联处方数据" />
        </div>
        
        <div v-else>
          <div v-for="(prescription, index) in prescriptionsList" :key="prescription.id || prescription._id" class="prescription-wrapper">
            <!-- 处方卡片 -->
            <el-card class="prescription-card" style="margin-bottom: 25px;">
              <template #header>
                <div class="prescription-header">
                  <div class="header-left">
                    <h3>处方 {{ index + 1 }}</h3>
                    <el-tag :type="getTypeTag(prescription.type)" size="default" class="type-tag">
                      {{ getTypeText(prescription.type) }}
                    </el-tag>
                    <el-tag :type="getStatusTag(prescription.status)" size="default" class="status-tag">
                      {{ getStatusText(prescription.status) }}
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <span class="prescription-id">处方编号：{{ prescription.prescriptionId || prescription.id || prescription._id }}</span>
                    <span class="created-time">开具时间：{{ formatDate(prescription.createdAt || prescription.createTime) }}</span>
                  </div>
                </div>
              </template>
              
              <div class="prescription-content">
                <!-- 基本信息区域 -->
                <div class="info-section">
                  <h4 class="section-title">
                    <el-icon><UserFilled /></el-icon>
                    基本信息
                  </h4>
                  <el-descriptions :column="3" border>
                    <el-descriptions-item label="开具医生" label-class-name="desc-label">
                      {{ prescription.doctorName || '未知' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="科室" label-class-name="desc-label">
                      {{ prescription.departmentName || '未知' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="处方状态" label-class-name="desc-label">
                      <el-tag :type="getStatusTag(prescription.status)" size="small">
                        {{ getStatusText(prescription.status) }}
                      </el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
                
                <!-- 诊断信息区域 -->
                <div class="info-section" v-if="prescription.diagnosis">
                  <h4 class="section-title">
                    <el-icon><Document /></el-icon>
                    诊断信息
                  </h4>
                  <div class="diagnosis-content">
                    <div v-if="Array.isArray(prescription.diagnosis)" class="diagnosis-tags">
                      <el-tag 
                        v-for="(diag, diagIndex) in prescription.diagnosis" 
                        :key="diagIndex"
                        type="primary"
                        class="diagnosis-tag"
                      >
                        {{ diag }}
                      </el-tag>
                    </div>
                    <div v-else class="diagnosis-text">
                      {{ prescription.diagnosis }}
                    </div>
                  </div>
                </div>
                
                <!-- 药品列表区域 -->
                <div class="info-section">
                  <h4 class="section-title">
                    <el-icon><FirstAidKit /></el-icon>
                    药品明细
                  </h4>
                  
                  <div v-if="prescription.items && prescription.items.length > 0" class="medications-list">
                    <div v-for="(item, itemIndex) in prescription.items" :key="itemIndex" class="medication-item">
                      <div class="medication-header">
                        <span class="medication-number">第{{ itemIndex + 1 }}种药品</span>
                        <el-tag type="info" size="small" v-if="item.drugId">ID: {{ item.drugId }}</el-tag>
                      </div>
                      
                      <el-descriptions :column="3" border class="medication-details">
                        <el-descriptions-item label="药品名称" label-class-name="med-label">
                          <span class="drug-name">{{ item.drugName || item.name || '未知药品' }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="规格/包装" label-class-name="med-label">
                          {{ item.specification || '未标明' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="单次剂量" label-class-name="med-label">
                          <span class="dosage">{{ item.dosage || '未标明' }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="用法频次" label-class-name="med-label">
                          <span class="frequency">{{ item.frequency || '未标明' }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="总数量" label-class-name="med-label">
                          <span class="quantity">{{ item.quantity || 0 }}</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="用药天数" label-class-name="med-label">
                          <span class="days">{{ item.days || '未标明' }}天</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="用药说明" :span="3" label-class-name="med-label" v-if="item.instructions">
                          <span class="instructions">{{ item.instructions }}</span>
                        </el-descriptions-item>
                      </el-descriptions>
                    </div>
                  </div>
                  
                  <div v-else class="no-medications">
                    <el-empty description="暂无药品信息" :image-size="60" />
                  </div>
                </div>
                
                <!-- 备注信息区域 -->
                <div class="info-section" v-if="prescription.remarks || prescription.advice || prescription.doctorAdvice">
                  <h4 class="section-title">
                    <el-icon><EditPen /></el-icon>
                    备注信息
                  </h4>
                  <div class="remarks-content">
                    <p v-if="prescription.remarks">
                      <strong>处方备注：</strong>{{ prescription.remarks }}
                    </p>
                    <p v-if="prescription.advice || prescription.doctorAdvice">
                      <strong>医嘱说明：</strong>{{ prescription.advice || prescription.doctorAdvice }}
                    </p>
                  </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="action-section">
                  <el-button type="primary" @click="printPrescription(prescription)" plain>
                    <el-icon><Printer /></el-icon>
                    打印处方
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { medicalRecordAPI, doctorAPI, departmentAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { ArrowLeft, Refresh, FirstAidKit, UserFilled, Document, EditPen, Printer } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()
const route = useRoute()

// 数据状态
const loading = ref(false)
const prescriptionsList = ref([])

// 查询参数
const queryParams = reactive({
  medicalRecordId: route.query.medicalRecordId || '',
  patientName: route.query.patientName || '',
  recordDate: route.query.recordDate || ''
})

// 获取处方类型标签
const getTypeTag = (type) => {
  if (type === 'western') return 'success'
  if (type === 'chinese') return 'warning'
  return 'info'
}

// 获取处方类型文本
const getTypeText = (type) => {
  if (type === 'western') return '西药处方'
  if (type === 'chinese') return '中药处方'
  return '未知类型'
}

// 获取状态标签
const getStatusTag = (status) => {
  const statusMap = {
    '待审核': 'warning',
    '已审核': 'success', 
    '已发药': 'primary',
    '已作废': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  return status || '未知状态'
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 刷新数据
const refreshData = () => {
  loadPrescriptions()
}

// 打印处方
const printPrescription = (prescription) => {
  const printWindow = window.open('', '_blank')
  if (!printWindow) {
    ElMessage.warning('请允许弹出窗口以打印处方')
    return
  }
  
  // 构建药品列表HTML
  let medicationsHtml = '<table border="1" cellspacing="0" cellpadding="8" style="width: 100%; border-collapse: collapse; margin: 15px 0;">'
  medicationsHtml += '<tr style="background-color: #f5f7fa;"><th>药品名称</th><th>规格</th><th>剂量</th><th>频次</th><th>数量</th><th>天数</th><th>说明</th></tr>'
  
  if (prescription.items && prescription.items.length > 0) {
    prescription.items.forEach(item => {
      medicationsHtml += `<tr>
        <td>${item.drugName || item.name || '未知'}</td>
        <td>${item.specification || '-'}</td>
        <td>${item.dosage || '-'}</td>
        <td>${item.frequency || '-'}</td>
        <td>${item.quantity || '0'}</td>
        <td>${item.days || '-'}</td>
        <td>${item.instructions || '-'}</td>
      </tr>`
    })
  } else {
    medicationsHtml += '<tr><td colspan="7" style="text-align: center;">无药品信息</td></tr>'
  }
  medicationsHtml += '</table>'
  
  // 构建打印内容
  const printContent = `
    <html>
      <head>
        <title>处方 - ${queryParams.patientName}</title>
        <style>
          body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
          h1 { text-align: center; margin-bottom: 20px; color: #333; }
          .header { border-bottom: 2px solid #ddd; padding-bottom: 15px; margin-bottom: 20px; }
          .info-item { margin-bottom: 8px; }
          .label { font-weight: bold; display: inline-block; width: 120px; }
          table { font-size: 14px; }
          th { background-color: #f5f7fa; font-weight: bold; }
          .footer { margin-top: 30px; border-top: 1px solid #ddd; padding-top: 15px; }
          .signature { text-align: right; margin-top: 40px; }
        </style>
      </head>
      <body>
        <h1>${getTypeText(prescription.type)}</h1>
        <div class="header">
          <div class="info-item"><span class="label">患者姓名：</span>${queryParams.patientName}</div>
          <div class="info-item"><span class="label">就诊日期：</span>${formatDate(queryParams.recordDate)}</div>
          <div class="info-item"><span class="label">处方编号：</span>${prescription.prescriptionId || prescription.id || prescription._id}</div>
          <div class="info-item"><span class="label">开具时间：</span>${formatDate(prescription.createdAt)}</div>
        </div>
        
        ${Array.isArray(prescription.diagnosis) ? 
          '<div class="info-item"><span class="label">诊断：</span>' + prescription.diagnosis.join('；') + '</div>' :
          '<div class="info-item"><span class="label">诊断：</span>' + (prescription.diagnosis || '无') + '</div>'
        }
        
        <h3>药品明细</h3>
        ${medicationsHtml}
        
        ${prescription.remarks ? `<div class="info-item"><span class="label">处方备注：</span>${prescription.remarks}</div>` : ''}
        ${prescription.advice ? `<div class="info-item"><span class="label">医嘱说明：</span>${prescription.advice}</div>` : ''}
        
        <div class="signature">
          <div>医生签名：__________________</div>
          <div style="margin-top: 10px;">药师签名：__________________</div>
          <div style="margin-top: 10px;">打印时间：${formatDate(new Date())}</div>
        </div>
      </body>
    </html>
  `
  
  printWindow.document.open()
  printWindow.document.write(printContent)
  printWindow.document.close()
  
  setTimeout(() => {
    printWindow.print()
    printWindow.close()
  }, 500)
}

// 查询医生信息
const getDoctorInfo = async (doctorId) => {
  if (!doctorId) return null
  
  try {
    console.log('查询医生信息, ID:', doctorId)
    const res = await doctorAPI.getDoctor(doctorId)
    if (res.success && res.data) {
      console.log('医生查询成功:', res.data)
      return res.data
    }
  } catch (error) {
    console.error('查询医生信息失败:', error)
  }
  return null
}

// 查询科室信息
const getDepartmentInfo = async (departmentId) => {
  if (!departmentId) return null
  
  try {
    console.log('查询科室信息, ID:', departmentId)
    const res = await departmentAPI.getDepartment(departmentId)
    if (res.success && res.data) {
      console.log('科室查询成功:', res.data)
      return res.data
    }
  } catch (error) {
    console.error('查询科室信息失败:', error)
  }
  return null
}

// 填充医生和科室信息
const fillDoctorAndDepartmentInfo = async (prescriptions) => {
  const doctorCache = new Map()
  const departmentCache = new Map()
  
  for (let prescription of prescriptions) {
    // 填充医生信息
    if (prescription.doctorId && !prescription.doctorName) {
      if (!doctorCache.has(prescription.doctorId)) {
        const doctorInfo = await getDoctorInfo(prescription.doctorId)
        doctorCache.set(prescription.doctorId, doctorInfo)
      }
      const doctorInfo = doctorCache.get(prescription.doctorId)
      if (doctorInfo) {
        prescription.doctorName = doctorInfo.name || '未知医生'
      }
    }
    
    // 填充科室信息
    if (prescription.departmentId && !prescription.departmentName) {
      if (!departmentCache.has(prescription.departmentId)) {
        const departmentInfo = await getDepartmentInfo(prescription.departmentId)
        departmentCache.set(prescription.departmentId, departmentInfo)
      }
      const departmentInfo = departmentCache.get(prescription.departmentId)
      if (departmentInfo) {
        prescription.departmentName = departmentInfo.name || '未知科室'
      }
    }
  }
  
  return prescriptions
}

// 加载处方数据
const loadPrescriptions = async () => {
  if (!queryParams.medicalRecordId) {
    ElMessage.error('缺少医疗记录ID参数')
    return
  }
  
  loading.value = true
  
  try {
    const res = await medicalRecordAPI.getRelatedData(queryParams.medicalRecordId)
    
    if (res.success && res.data) {
      let prescriptions = res.data.prescriptions?.items || res.data.prescriptions || []
      
      console.log('处方数据加载完成:', prescriptions)
      
      if (prescriptions.length > 0) {
        // 填充医生和科室信息
        prescriptions = await fillDoctorAndDepartmentInfo(prescriptions)
        console.log('填充医生科室信息后:', prescriptions)
      }
      
      prescriptionsList.value = prescriptions
      
      if (prescriptionsList.value.length === 0) {
        ElMessage.info('该医疗记录暂无关联处方')
      }
    } else {
      ElMessage.error('获取处方数据失败')
    }
  } catch (error) {
    console.error('加载处方数据失败:', error)
    ElMessage.error('加载处方数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadPrescriptions()
})
</script>

<style scoped>
.doctor-prescriptions {
  width: 100%;
  overflow-x: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-info h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 20px;
}

.breadcrumb-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.prescription-wrapper {
  margin-bottom: 25px;
}

.prescription-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.prescription-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.type-tag {
  font-weight: 500;
}

.status-tag {
  font-weight: 500;
}

.header-right {
  text-align: right;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.prescription-id {
  display: block;
  font-weight: 500;
}

.created-time {
  display: block;
  margin-top: 4px;
}

.prescription-content {
  padding: 10px 0;
}

.info-section {
  margin-bottom: 25px;
}

.section-title {
  margin: 0 0 15px 0;
  color: #409EFF;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 8px;
}

:deep(.desc-label) {
  font-weight: 600;
  color: #606266;
}

.diagnosis-content {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.diagnosis-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.diagnosis-tag {
  font-size: 14px;
  padding: 6px 12px;
}

.diagnosis-text {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
}

.medications-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.medication-item {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.medication-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.medication-number {
  font-weight: 600;
  color: #409EFF;
  font-size: 15px;
}

.medication-details {
  background-color: white;
  border-radius: 4px;
}

:deep(.med-label) {
  font-weight: 500;
  color: #606266;
  font-size: 13px;
}

.drug-name {
  font-weight: 600;
  color: #303133;
}

.dosage, .frequency, .quantity, .days {
  font-weight: 500;
  color: #409EFF;
}

.instructions {
  color: #909399;
  font-style: italic;
}

.no-medications {
  text-align: center;
  padding: 20px;
}

.remarks-content {
  padding: 15px;
  background-color: #fff9e6;
  border-radius: 6px;
  border-left: 4px solid #e6a23c;
}

.remarks-content p {
  margin: 8px 0;
  line-height: 1.6;
  color: #303133;
}

.action-section {
  text-align: right;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .header-actions {
    justify-content: flex-end;
  }
  
  .breadcrumb-info {
    flex-direction: column;
    gap: 5px;
  }
  
  .prescription-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-left {
    flex-wrap: wrap;
  }
  
  .header-right {
    text-align: left;
  }
}
</style> 